﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using DataLayer.Entities;
using DataLayer.Implementations;
using DonutMgmtSystemFoundation.Helpers.CircularList;
using DonutMgmtSystemFoundation.Models;

namespace DonutMgmtSystemFoundation.Helpers
{
    public class CalendarHelper
    {
        public List<CalendarEventModel> GetEvents()
        {
            List<CalendarEventModel> events = new List<CalendarEventModel>(); // Calendar events list

            UserOrderApplication userApp = new UserOrderApplication();
            IList<UserOrder> users = userApp.GetActiveUsersOrderedByUserOrder();

            if (users.Count > 0)
            {
                int addMonths = Int32.Parse(ConfigurationManager.AppSettings["CalendarMonths"]);
                int usersPerDay = Int32.Parse(ConfigurationManager.AppSettings["UsersPerDay"]);
                int userId = Int32.Parse(ConfigurationManager.AppSettings["StartUserId"]);

                DateTime startDate = DateTime.Parse(ConfigurationManager.AppSettings["StartDate"]);

                DateTime stopDate = DateTime.Today.AddMonths(addMonths);
                DateTime currentDate = startDate;
                int daysUntilFriday = ((int)DayOfWeek.Friday - (int)currentDate.DayOfWeek + 7) % 7;
                currentDate = currentDate.AddDays(daysUntilFriday);
                int currentId = 0;
                CircularLinkedList<UserOrder> list = new CircularLinkedList<UserOrder>(users);
                Node<UserOrder> currentNode = list.Head;
            
                // Elegir usuario inicial
                while (currentNode.Value.User.UserId != userId)
                {
                    currentNode = currentNode.Next;
                }

                while (currentDate < stopDate)
                {
                    for (int i = 0; i < usersPerDay; i++)
                    {
                        UserOrder current = currentNode.Value;
                        currentDate = currentDate.AddMinutes(i);
                        // Create Event
                        CalendarEventModel cEvent = new CalendarEventModel()
                        {
                            id = ++currentId,
                            title = current.User.Name,
                            start = currentDate.ToString("yyyy-MM-dd hh:mm:ss"),
                            Email = current.User.Email
                        };

                        events.Add(cEvent);
                        currentNode = currentNode.Next;
                    }

                    currentDate = currentDate.AddMinutes((usersPerDay - 1) * -1).AddDays(7); // Add a week and substract minutes added
                }

            }

            return events;
        }
    }
}